import os
import sys
import string

def getlongpath(basepath):
    workdir = basepath
    nextdir = os.listdir(workdir)
    while os.path.isdir(workdir+'/'+nextdir[0]):
        workdir = workdir +'/'+nextdir[0] #suppose only one sub dir
        nextdir = os.listdir(workdir)
    return workdir

def rmdir(basepath):
    workdir = basepath
    rm_cmd = 'rm -r '+workdir +'/home/' #suppose only one sub dir
    os.popen(rm_cmd)

def getIDfile(srcpath,despath,file_names):
    #fp = open('info.txt','w')
    tmp_path = despath+'/tmp_data'
    mk_tmp_cmd ='mkdir '+ tmp_path
    os.popen(mk_tmp_cmd)
    for tarfiles in os.listdir(srcpath): # iterate every tar file
        tarpath = srcpath + '/' +tarfiles
        if os.path.isfile(tarpath):
            ftm = tarfiles.split('.') # get the id of job
            if len(ftm)==3 and str.isdigit(ftm[0]) and ftm[1]=="tar" and ftm[2]=="bz2":
                #tmppath = despath+'/tmp_data' # tmp dir to store all the extracted files
     	        de_cmd = 'tar -xjf '+tarpath+' -C '+tmp_path
    	        os.popen(de_cmd)
                
    	        longpath = getlongpath(tmp_path)
    	        datapath = despath +'/'+ftm[0]  # create id dir 
    	        mkfile_cmd ='mkdir '+ datapath
    	        os.popen(mkfile_cmd)
		
		
    	        for files in file_names:
    	            filepath = longpath+'/'+files
    	            if os.path.exists(filepath) == True:
    	                cpfile_cmd = 'cp '+filepath+' '+datapath+'/'
                        os.popen(cpfile_cmd)
                    '''
                    else:
    	                info = ftm[0]+': '+files+' not exists'+"\n"
                        print info
                        fp = open('info_12_06_201709.txt','a')
                        fp.write(info)
                        fp.close()
                    '''
            '''
    	    logflag = 0
	        for logfiles in os.listdir(longpath): # all files in the longpath
		    if logfiles.endswith('.log'):
		        logpath = longpath+'/'+logfiles
			cplog_cmd = 'cp '+logpath+' '+datapath+'/'
			os.popen(cplog_cmd)
			logflag = 1    
	        
		    if logflag == 0:
		    loginfo = ftm[0]+': logfile not exists'+"\n"
		    print loginfo
	            lfp = open('loginfo_4_14.txt','a')
		    lfp.write(loginfo)
		    lfp.close()
		    '''
        rmdir(tmp_path)
    rm_tmp = 'rm -r '+ tmp_path
    os.popen(rm_tmp)
    #fp.close()


if __name__ == "__main__":
    #SRCPATH = "/home/lss/vasp_raw_data/FINISHED"
    #DESPATH = "/home/lss/201711_extract_data"
    SRCPATH = sys.argv[1]
    DESPATH = sys.argv[2]
    #file_names = ['OUTCAR','POSCAR','KPOINTS','POTCAR','INCAR']
    file_names = ['OUTCAR','KPOINTS']
    getIDfile(SRCPATH,DESPATH,file_names)
    
